package forms;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import common.Command;
import connect.Config;
import elements.Account;

class Request extends Thread{
	private Socket socket;
	private Account account;
	public boolean success=false;
	DataInputStream dis;
	DataOutputStream dos;
	public String error=null;
	Signup signup;
	public Request(Signup signup,Account account)throws Exception{
		socket=new Socket(Config.SERVER_NAME,Config.SERVER_PORT);
		this.account=account;
		this.signup=signup;
	}
	public void shutdown()throws Exception{
		dis.close();
		dos.close();
		socket.close();
	}
	public void run(){
		try {
			dis=new DataInputStream(socket.getInputStream());
			dos=new DataOutputStream(socket.getOutputStream());
			dos.write(Command.REQUEST_SIGN_UP);
			dos.writeUTF(account.getNickName());
			dos.writeUTF(account.getPassword());
			dos.writeUTF(account.getRealName());
			dos.flush();
			int com=dis.read();
			if(com!=Command.REQUEST_SIGN_UP)throw new Exception("Có lỗi không xác định từ server");
			int ret=dis.read();
			if(ret==Command.RETURN_SUCCESS){
				success=true;
			}else{
				throw new Exception(dis.readUTF());
			}
		} catch (Exception e) {
			error=e.getMessage();
		}finally{
			signup.processDone();
		}
	}
}
@SuppressWarnings("serial")
public class Signup extends JDialog implements ActionListener{
	public boolean success=false;
	private JButton btCancel=new JButton("Hủy bỏ");
	private Account account;
	private Request request=null;
	public Signup(Account account){
		super();
		setLayout(new FlowLayout());
		setTitle("Đăng ký tài khoản");
		add(new JLabel("Đang thực hiện yêu cầu"));
		JProgressBar jpb=new JProgressBar();
		jpb.setIndeterminate(true);
		setModal(true);
		add(jpb);
		add(btCancel);
		setLocation(350,300);
		pack();
		btCancel.addActionListener(this);
		this.account=account;
		this.addWindowListener(new WindowAdapter(){
			public void windowOpened(WindowEvent e) {
				try{
					request=new Request(Signup.this,Signup.this.account);
					request.start();
				}catch(Exception ex){
					JOptionPane.showMessageDialog(Signup.this, "Kết nối đến server thất bại.\n"+ex.getMessage());
					Signup.this.setVisible(false);
					return;
				}
			}
		});
	}
	public void processDone(){
		if(request.success){
			success=true;
			JOptionPane.showMessageDialog(this, "Đăng ký tài khoản mới thành công.");
		}
		this.setVisible(false);
	}
	public void actionPerformed(ActionEvent arg0) {
		request.interrupt();
		processDone();
	}
}

